package cn.tedu.fruitshop.controller;

import cn.tedu.fruitshop.pojo.dto.CommentAddNewDTO;
import cn.tedu.fruitshop.pojo.dto.CommentUpdateDTO;
import cn.tedu.fruitshop.pojo.vo.CommentListItemVO;
import cn.tedu.fruitshop.service.ICommentService;
import cn.tedu.fruitshop.web.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Slf4j
@Validated
@RestController
@RequestMapping("/comments")
@Api(tags = "09. 评论管理模块")
public class CommentController {
    @Autowired
    private ICommentService commentService;

    public CommentController() {
        log.debug("创建控制器对象：CommentController");
    }

    // http://localhost:8080/comments/add-new?name=评论001&description=评论001的简介&sort=199
    @ApiOperation("添加评论")
    @ApiOperationSupport(order = 100)
    @PostMapping("/add-new")
    public JsonResult<Void> addNew(@Valid CommentAddNewDTO commentAddNewDTO) {
        log.debug("开始处理【添加评论】的请求，参数：{}", commentAddNewDTO);
        commentService.addNew(commentAddNewDTO);
        log.debug("添加评论成功！");
        return JsonResult.ok();
    }

    // http://localhost:8080/comments/9527/delete
    @ApiOperation("根据id删除评论")
    @ApiOperationSupport(order = 200)
    @ApiImplicitParam(name = "id", value = "评论id", required = true, dataType = "Integer")
    @PostMapping("/{id:[0-9]+}/delete")
    public JsonResult<Void> delete(@Range(min = 1, message = "删除评论失败，尝试删除的评论的ID无效！")
                                   @PathVariable Integer id) {
        log.debug("开始处理【根据id删除评论】的请求，参数：{}", id);
        commentService.delete(id);
        return JsonResult.ok();
    }

    // http://localhost:8080/comments
    @ApiOperation("根据商品id查询评论列表")
    @ApiOperationSupport(order = 420)
    @GetMapping("")
    public JsonResult<List<CommentListItemVO>> list(Integer itemId) {
        log.debug("开始处理【查询评论列表】的请求，参数为:{}",itemId);
        List<CommentListItemVO> list = commentService.list(itemId);
        return JsonResult.ok(list);
    }


    @ApiOperation("修改评论详情")
    @ApiOperationSupport(order = 300)
    @ApiImplicitParam(name = "id", value = "评论id", required = true, dataType = "long")
    @PostMapping("/{id:[0-9]+}/update")
    public JsonResult<Void> updateById(@PathVariable int id, CommentUpdateDTO commentUpdateDTO) {
        log.debug("开始处理【修改评论详情】的请求，参数ID：{}, 新数据：{}", id, commentUpdateDTO);
        commentService.updateInfoById(id, commentUpdateDTO);
        return JsonResult.ok();
    }
}
